import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/mine/mine_mod/mine_modavatar.dart';
import 'package:find_friend/pages/mine/mine_tags.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:intl/intl.dart';

import 'mine_mod/mine_modsign.dart';

class MineUserInfoDetailPage extends StatefulWidget {
  @override
  _MineUserInfoDetailPageState createState() => _MineUserInfoDetailPageState();
}

class _MineUserInfoDetailPageState extends State<MineUserInfoDetailPage> {

  SharedUserInfo _userInfo = SharedUserInfo();
  bool isupdate = false;
  @override
  void initState() {
    super.initState();
    _initData();
  }

  _initData() async {
    final user = await SharedUserInfo.instance();
    _userInfo = user;
    if(mounted) setState(() {});
  }

  _reloadData() {
    isupdate = true;
    _initData();
  }

  _request(DateTime dateTime) {
    String val = DateFormat('yyyy-MM-dd').format(dateTime);
    Networktool.request(API.edit, params: {"birthday": val}, success: (data){
      print(data);
      if(data["data"] != null) {
        SharedUserInfo.saveData(data);
        AlertTool.showToast("修改成功");
        EventMineBus.instance.commit(EventMineKeys.UpdateMineInfo, null);
        _reloadData();
      }
    },
    fail: (msg) => AlertTool.showToast(msg));
  }

  // 修改标签
   _requestLabel(String label) {
     _userInfo.label.remove(label);
    String temp = _userInfo.label.join(",");
    Networktool.request(API.edit, params: {"label": temp}, success: (data){
      print(data);
      if(data["data"] != null) {
        SharedUserInfo.saveData(data);
        EventMineBus.instance.commit(EventMineKeys.UpdateMineInfo, null);
        _initData();
      }
    },
    fail: (msg) => AlertTool.showToast(msg));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: APP_scaffold_back_color,
      appBar: AppBar(
        title: Text("详细资料"),
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(
          onPressed: (){
            Navigator.of(context).pop(isupdate);
          },
          icon: Image.asset("assets/fanhui.png"),
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: const EdgeInsets.all(10),
          child: Column(
            children: [
              Container(
                height: 75,
                padding: const EdgeInsets.symmetric(horizontal: 5.5),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color:const Color(0xffdddddd), width: 0.5)
                ),
                child: GestureDetector(
                  onTap: () async {
                   bool update =  await push(context, MineModAvatarPage(avatar: _userInfo.avatar));
                   if(update == true)_reloadData();
                  },
                  child: Container( // 加一个container方便点击s
                    color: Colors.white,
                    child: Row(
                      children: [
                        Expanded(child: Text("头像", style: instanceTextStyle(15, APP_font_black),)),
                        CustomCircleAvatar(size: 41.w, url: _userInfo.avatar,),
                        SizedBox(width: 10,),
                        Image.asset("assets/my-next.png")
                      ],
                    ),
                  ),
                )
              ),
              SizedBox(height: 10,),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 5.5),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color:Color(0xffdddddd), width: 0.5)
                ),
                child: Column(
                  children: [
                    MineInfoCell("昵称", detail: _userInfo.nickname ?? "昵称", isShowArrow: true,callback: (){
                      Navigator.of(context).pushNamed("/minemodname");
                    },),
                    MineInfoCell("性别", detail: _userInfo.gender == 1 ? "男" : "女"),
                    MineInfoCell("出生日期", detail: _userInfo.birthday ?? "2000年11月11日", isShowArrow: true,callback: (){
                      DatePicker.showDatePicker(context,
                        showTitleActions: true,
                        minTime: DateTime(1970, 3, 5),
                        theme: DatePickerTheme(doneStyle: instanceTextStyle(15 ,APP_main_color, fontWeight: FontWeight.w500)),
                        maxTime: DateTime.now(), 
                        onConfirm: _request, 
                        currentTime: DateFormat("yyyy-MM-dd").parse(_userInfo.birthday), 
                        locale: LocaleType.zh);
                      }
                    ),
                    // MineInfoCell("年龄", detail: _userInfo.age ?? "19",),
                    MineInfoCell("星座", detail: _userInfo.zodiac ?? "天蝎座",),
                    MineInfoCell("生肖", detail: _userInfo.zodiacC ?? "龙",),
                    MineInfoCell("五行", detail: _userInfo.wuxing ?? "五行",),
                  ],
                ),
              ),
              SizedBox(height: 10,),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 5.5),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color:const Color(0xffdddddd), width: 0.5)
                ),
                child: Column(
                  children: [
                    MineInfoCell(
                      "我的个签", 
                      detail: _userInfo.bio ?? "我的个性签名", 
                      detailFontSize: 12,
                      detailColor: APP_font_grey,
                      isShowArrow: true,
                      callback: () async {
                        bool isupdate = await push(context, MineModSignPage());
                        if(isupdate == true) _initData();
                      },
                    ),
                    MineInfoCell("我的学校", detail: _userInfo.schoolname ?? "暂无", isShowArrow: true,),
                    _MineInfoTagCell(
                      tags: _userInfo?.label ?? [], 
                      onUpdate: () => _initData(),
                      onDelegateLabel: _requestLabel,
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

 class MineInfoCell extends StatelessWidget {
   final Function callback;
   final String title;
   final String detail;
   final Color detailColor;
   final double detailFontSize;
   final bool isShowArrow;
   final double titleFontSize;
   final double detailRightPadding;

  const MineInfoCell(
    this.title,
    {
    Key key, 
    this.isShowArrow = false,
    this.callback, 
    this.detail = "",
    this.detailColor,
    this.detailFontSize = 14,
    this.titleFontSize = 15,
    this.detailRightPadding = 10,
    }) : super(key: key);

    @override
    Widget build(BuildContext context) {
      final size = MediaQuery.of(context).size;
      return GestureDetector(
        onTap: callback,
        child: Container(
          height: 35.h,
          color: Colors.transparent,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(child: Text(title, style: instanceTextStyle(titleFontSize, APP_font_black),)),
              Container(
                width: size.width * 0.5,
                alignment: Alignment.centerRight,
                padding: EdgeInsets.only(right: detailRightPadding),
                child: Text(detail, maxLines: 1, overflow: TextOverflow.ellipsis, style: instanceTextStyle(detailFontSize, detailColor ?? APP_font_black),),
              ),
              isShowArrow ? Image.asset("assets/my-next.png") : Container(width: 6,)
            ],
          ),
        ),
      );
    }
  }

class _MineInfoTagCell extends StatelessWidget {

  final Function onTap;
  List<String> tags;
  final Function() onUpdate;
  final Function(String label) onDelegateLabel;

  _MineInfoTagCell({Key key, this.onTap, this.onDelegateLabel, this.tags, this.onUpdate}) : super(key: key);

  _update() {
    if(onUpdate != null) onUpdate();
  }

  @override
  Widget build(BuildContext context) {
    
    final size = MediaQuery.of(context).size;

    return GestureDetector(
        onTap: () async {
          bool isupdate = await push(context, MineTags(mineTags: tags));
          if(isupdate) _update();
        },
        child: Container(
          padding: const EdgeInsets.only(bottom: 10, top: 10),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(child: Text("我的标签", style: instanceTextStyle(15, APP_font_black),)),
              Container(
                width: size.width * 0.5,
                padding: const EdgeInsets.only(right:10.0,),
                child: Wrap(
                  direction: Axis.horizontal,
                  alignment: WrapAlignment.end,
                  spacing: 10,
                  runSpacing: 5,
                  children: tags.map((e) => 
                    _MineTagCell(title: e,)
                ).toList(),
                )
              ),
              Image.asset("assets/my-next.png")
            ],
          ),
        ),
      );
  }
}

class _MineTagCell extends StatelessWidget {

  final String title;

  const _MineTagCell({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    double itemW = (size.width * 0.5 - 20 - 40) / 3.0;
    return Container(
      alignment: Alignment.center,
      width: itemW + 10,
      padding: const EdgeInsets.only(bottom: 1.5, left: 5, right: 5),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/xuxie.png",),
          fit: BoxFit.fill
        )
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Expanded(
            child: Text(
              title, 
              maxLines: 1, 
              textAlign: TextAlign.center,
              overflow: TextOverflow.ellipsis, style: instanceTextStyle(12, APP_main_color),)),
        ],
      ),
    );
  }
}